package com.geticsen.leetcode;
//https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
public class Solution_34 {
    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        int start = 0;
        int end = nums.length - 1;
        int middle = 0;
        if (nums.length < 1 || target < nums[start] || target > nums[end]) {
            return res;
        }
        while (start <= end) {
            middle = (start + end) / 2;
            if (nums[middle] == target) {
                break;
            } else if (nums[middle] < target) {
                start = middle + 1;
            } else {
                end = middle - 1;
            }
        }
        if (nums[middle] == target) {
            start = middle;
            end = middle;
            while (start >= 0) {
                if (nums[start] == target) {
                    start--;
                }else{
                    break;
                }
            }
            while (end <= nums.length - 1) {
                if (nums[end] == target) {
                    end++;
                }else{
                    break;
                }
            }
            res[0] = Math.max(start+1, 0);
            res[1] = Math.min(end-1, nums.length - 1);
        }
        return res;
    }
}
